﻿using System;
using Autofac;
using ShuttleBus.AdminMessages;
using ShuttleBus.Subscriptions;

namespace ShuttleBus.Config
{
    public class TransportConfiguration
    {
        internal TransportConfiguration()
        {
        }

        /// <summary>
        /// Adds subscriptions to messages I want to recieve
        /// </summary>
        /// <returns></returns>
        public TransportConfiguration WithSubscriptionsTo(Action<IAddSubscriptions> subscriptions)
        {
            var publisher = UnitOfWork.Instance.ApplicationContainer.Resolve<IAddSubscriptions>();
            subscriptions.Invoke(publisher);
            /*var repository = UnitOfWork.Instance.ApplicationContainer.Resolve<ISubscriptionRepository>();
            subscriptions.Invoke(repository);*/
            return this;
        }

        public IBus Start()
        {
            var bus = UnitOfWork.Instance.ApplicationContainer.Resolve<IBus>();
            bus.Start();
            return bus;
        }
    }

    public class SubscriptionPublisher : IAddSubscriptions
    {
        private readonly IBus _bus;

        public SubscriptionPublisher(IBus bus)
        {
            _bus = bus;
        }

        public void Add(Subscription subscription)
        {
            _bus.Send(subscription.Location, new AddSubscriptionMessage
                {
                    MessageType = subscription.MessageType,
                    Sender = subscription.Location.ToString()
                });
        }
    }
}